package club.lovety.oauth2.config;

import club.lovety.oauth2.filter.OauthFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import javax.annotation.Resource;
import javax.servlet.Filter;


@Configuration
public class Oauth2WebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

    private static final Logger log = LoggerFactory.getLogger(Oauth2WebSecurityConfigurerAdapter.class);

    @Resource
    private Oauth2UserDetailsService oauth2UserDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(oauth2UserDetailsService);
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().and().formLogin().loginPage("/login").permitAll().and().csrf().disable();
    }

    public Filter OauthFilter(){
//        CompositeFilter filter = new CompositeFilter();
//        List filters = new ArrayList<>();
////        filters.add(ssoFilter(github(), "/login/github"));
////        filter.setFilters(filters);
//        return filter;
        return new OauthFilter();
    }

//    private Filter ssoFilter(OAuth2ProtectedResourceDetails client, String path) {
//        OAuth2ClientAuthenticationProcessingFilter filter = new OAuth2ClientAuthenticationProcessingFilter(path);
//        OAuth2RestTemplate template = new OAuth2RestTemplate(client.getClient(), oauth2ClientContext);
//        filter.setRestTemplate(template);
//        UserInfoTokenServices tokenServices = new UserInfoTokenServices(
//                client.getResource().getUserInfoUri(), client.getClient().getClientId());
//        tokenServices.setRestTemplate(template);
//        filter.setTokenServices(tokenServices);
//        return filter;
//    }

//    @Bean
//    public FilterRegistrationBean registration(BasicAuthenticationFilter filter) {
//        FilterRegistrationBean registration = new FilterRegistrationBean(filter);
//        registration.setEnabled(false);
//        return registration;
//    }
//
//    @Bean
//    public BasicAuthenticationFilter getBasicAuthenticationFilter() throws Exception {
//        return new BasicAuthenticationFilter(authenticationManagerBean());
//    }
}
